import {
  formatDate,
  formatDate2,
  formatDuration
} from '../../utils/date'
const app = getApp()
const domain = app.globalData.domain

// pages/warningReport/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    editMode: true,
    createTimeVis: false,
    nodeDialogVis: false,
    confNodes: [],
    nodeVal: {
      name: null
    },
    data: {},
    currentNode: null,
    kvData: {},
    hiddenIds: [],
    deviceOptions: []
  },
  onZhibiaoConfirm(e) {
    console.log('onZhibiaoConfirm', e)

    const kvMap = e?.detail?.value?.[0]?.kvMap || {}
    const kvData = {
      ...(this.data.kvData || {}),
      ...kvMap
    }
    console.log('kvMap', kvMap)
    console.log('kvData', kvData)
    this.setData({
      kvData
    })
  },
  openDiviceSelect() {
    this.setData({
      deviceSelectVis: true
    })
  },
  checkInclude(e) {
    console.log('checkInclude', e)
  },
  toggleItem(e) {
    const {
      id,
    } = e.currentTarget.dataset
    const editNodeLoop = (confNodes, id) => {
      console.log('editNodeLoop', confNodes, id)
      confNodes?.forEach((node, index) => {
        if (node.id === id) {
          confNodes[index] = {
            ...node,
            hidden: !node.hidden
          }
          console.log('找到', node)
        } else {
          editNodeLoop(node?.confNodes, id)
        }
      })
    }

    const confNodes = [
      ...this.data.confNodes
    ]
    console.log('confNodes', confNodes)
    editNodeLoop(confNodes, id)
    console.log('edit-newData', confNodes)
    this.setData({
      confNodes,
    })
  },
  deleteNode(e) {
    const {
      id,
    } = e.currentTarget.dataset
    const confNodes = this.data.confNodes

    function filterNode(nodes, id) {
      console.log('filterNode', nodes, id)
      nodes = nodes?.filter(item => item.id !== id)
      nodes.forEach((node, index) => {
        if (node.confNodes?.length > 0) {
          nodes[index].confNodes = filterNode(node.confNodes, id)
        }
      })
      return nodes
    }

    const result = filterNode(confNodes, id)
    console.log('deleteNode', result)
    this.setData({
      confNodes: result
    })
  },
  setNodeByid(vals, id) {
    const confNodes = this.data.confNodes
    console.log(confNodes)
    let target

    confNodes.forEach((item, index) => {
      if (item.id == id) {
        confNodes[index] = {
          ...target,
          ...vals
        }
      }
    })

    console.log('set', vals, target, confNodes)
    return confNodes
  },
  addNodeByid(vals, id) {
    const confNodes = this.data.confNodes
    console.log(confNodes)
  },
  nodeConfirm(e) {
    if (!this.data.nodeVal.name) {
      wx.showToast({
        title: '请输入名称',
        icon: 'none'
      })
      return
    }

    if (!this.data.nodeVal.code) {
      wx.showToast({
        title: '请选择业务类型',
        icon: 'none'
      })
      return
    }
    const {
      op,
      id,
      odata
    } = this.data.currentNode
    console.log('this.data.currentNode', this.data.currentNode)
    console.log('this.data.confNodes', this.data.confNodes)
    console.log('odata', odata)
    if (op === 'edit') {
      const editNodeLoop = (confNodes, id) => {
        confNodes?.forEach((node, index) => {
          if (node.id === id) {
            console.log('editNodeLoop', node, confNodes, id)
            confNodes[index] = {
              ...node,
              name: this.data.nodeVal.name,
              // type: this.data.nodeVal.dictCode,
              code: this.data.nodeVal.code,
              kvMap: this.data.kvData,
              kvMeta: this.data.kvMeta
            }
            console.log('找到', node)
          } else {
            editNodeLoop(node?.confNodes, id)
          }
        })
      }

      const confNodes = [
        ...this.data.confNodes
      ]
      console.log('confNodes', confNodes)
      editNodeLoop(confNodes, id)
      console.log('edit-newData', confNodes)
      this.setData({
        confNodes,
        nodeDialogVis: false,
        nodeVal: {}
      })
    } else {
      const addNodeLoop = (confNodes, id) => {
        console.log('addNodeLoop', confNodes, id)
        confNodes?.forEach((node) => {
          if (node.id === id) {
            if (!node?.confNodes) node.confNodes = []
            node.confNodes.push({
              id: +new Date(),
              type: this.data.nodeVal.dictCode,
              name: this.data.nodeVal.name,
              code: this.data.nodeVal.code,
              unit: this.data.nodeVal.unit,
              kvMap: this.data.kvData,
              kvMeta: this.data.kvMeta,
              refObjectKey: this.data.nodeVal.refObjectKey,
              refObject: this.data.nodeVal.refObject,
            })
          } else {
            addNodeLoop(node?.confNodes, id)
          }
        })
      }


      const confNodes = [
        ...(this.data.confNodes || [])
      ]

      if (id) {
        addNodeLoop(confNodes, id)
      } else {
        confNodes.push({
          id: +new Date(),
          type: this.data.nodeVal.dictCode,
          name: this.data.nodeVal.name,
          code: this.data.nodeVal.code,
          kvMap: this.data.kvData,
          kvMeta: this.data.kvMeta,
          refObjectKey: this.data.nodeVal.refObjectKey,
          refObject: this.data.nodeVal.refObject,
        })
      }

      console.log('confNodes', confNodes)
      this.setData({
        confNodes,
        nodeDialogVis: false,
        nodeVal: {}
      })
    }
  },
  openNodeDialogVis(e) {
    const {
      id,
      op,
      odata,
      dict,
      parentdict,
      parentvalue
    } = e.currentTarget.dataset
    console.log('openNodeDialogVis', e.currentTarget.dataset, odata)
    console.log('odata', odata)
    console.log('dict', dict)
    if (op === 'edit') {
      this.setData({
        nodeDialogVis: true,

      })
      setTimeout(() => {
        this.setData({
          currentDict: dict,
          nodeVal: odata,
          currentNode: {
            id,
            op,
            odata
          },
          kvData: odata?.kvMap
        })
      }, 100)

    } else {
      this.setData({
        currentDict: dict,
        nodeDialogVis: true,
        currentNode: {
          id,
          op,
          odata
        }
      });
    }

    if (parentdict && parentvalue) {
      this.initDict({
        dict,
        parentDict: parentdict,
        parentValue: parentvalue,
      }, (dictData) => {
        console.log('dictData', dictData, odata?.code)
        if (odata?.code && op === 'edit') {
          const {
            kvMeta = []
          } = dictData?.find(item => item.value == odata.code) || {}
          console.log('kvMeta', kvMeta)
          this.setData({
            kvMeta
          })
        } else {
          const {
            kvMeta = [],
              name,
              dictCode,
              value,
              unit,
              refObjectKey,
              refObject
          } = dictData?.[0] || {}
          console.log('add', dictData, kvMeta)
          const kvData = {}
          kvMeta?.forEach(item => {
            if (item.customValue) {
              kvData[item.code] = item.customValue
            }
          })
          console.log('kvData', kvData)
          const nodeVal = {
            code: value,
            name,
            dictCode,
            unit,
            refObjectKey,
            refObject
          }
          console.log('nodeVal', nodeVal)
          setTimeout(() => {
            this.setData({
              kvMeta,
              kvData,
              nodeVal
            })
          }, 100)

          if (dictCode && value) {
            this.initDictDeviceList({
              dictValue: value,
              dictCode
            })
            return
          }
        }
      })
    }

    console.log('initDictDeviceList', odata)
    if (op === 'edit' && odata?.code && dict) {
      console.log('code,type', odata.code, dict)
      this.initDictDeviceList({
        dictValue: odata.code,
        dictCode: dict
      })
    }
  },
  closeNodeDialogVis() {
    this.setData({
      nodeDialogVis: false,
      nodeVal: {},
      currentDictData: [],
      kvMeta: [],
      kvData: {}
    });
  },
  changeMode(e) {
    this.setData({
      editMode: e.detail.value,
    });
  },
  onBack() {
    wx.navigateBack({
      delta: 1 // 这里的delta表示返回的页面数，如果 delta 大于现有页面数，则返回到首页
    });
  },
  showPicker(e) {
    console.log(1)
    this.setData({
      createTimeVis: true
    });
  },
  hidePicker() {
    const {
      mode
    } = this.data;
    this.setData({
      [`${mode}Visible`]: false,
    });
  },
  onConfirm(e) {
    const {
      value
    } = e.detail;

    console.log('confirm', value);
    const data = {
      ...this.data.data
    }
    data.createTime = value
    this.setData({
      data
    });

    this.hidePicker();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('options', options)
    this.setData({
      options
    })

    if (options.id) this.init(options.id)
    this.initDict({
      dict: 'industry'
    })
  },
  init(id) {
    wx.request({
      url: `${domain}/admin-api/smc/scene-conf/get?id=${id}`,
      data: {
        id
      },
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        if (res?.data?.code == '401') {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }
        console.log('res', res)
        const data = res?.data?.data
        const confNodes = res?.data?.data.confNodes
        if (data.createTime) data.createTime = formatDate2(data.createTime)
        this.setData({
          data,
          confNodes: confNodes
        })
      }
    })
  },
  initDict({
    dict = '',
    parentDict = '',
    parentValue = ''
  }, callback) {
    wx.request({
      url: `${domain}/admin-api/smc/tech-dict/tech-dict-data/list-by-dict-code`,
      data: {
        parentDict,
        dict,
        parentValue
      },
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        if (res?.data?.code == '401') {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }
        console.log('res', res)
        const data = res?.data?.data
        if (callback) callback(data)
        this.setData({
          [dict]: data,
          currentDictData: data
        })
      }
    })
  },
  initDictDeviceList(params) {
    wx.request({
      url: `${domain}/admin-api/smc/tech-node-profile/list`,
      data: params,
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        if (res?.data?.code == '401') {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }
        console.log('res', res)
        const data = res?.data?.data
        const dictDeviceList = data.map(item => {
          return {
            label: item.name,
            value: item
          }
        })
        this.setData({
          dictDeviceList
        })
      }
    })
  },
  changeValue(e) {
    console.log(e)
    const value = e.detail.value
    console.log(e)
    const data = this.data.data;
    const {
      target
    } = e.currentTarget.dataset
    data[target] = value
    console.log('data', data, target, value)
    this.setData({
      data
    })
  },
  changeKvData(e) {
    console.log('changeKvData', e)
    const value = e.detail.value
    const kvData = this.data.kvData;
    const {
      code
    } = e.currentTarget.dataset
    kvData[code] = value
    console.log('data', kvData, code, value)
    this.setData({
      kvData
    })
  },
  changeNodeVal(e) {
    const value = e.detail.value
    console.log('changeNodeVal', e, e.currentTarget.dataset)
    const nodeVal = this.data.nodeVal;
    const {
      target,
      dict
    } = e.currentTarget.dataset
    nodeVal[target] = value
    console.log('data', nodeVal, target, value)

    if (dict) {
      console.log('更改dict value', value)
      this.initDict(dict)
    }

    if (target === 'code') {
      const {
        kvMeta = [],
          name,
          dictCode,
          refObject,
          refObjectKey
      } = this?.data?.currentDictData?.find(item => item.value == value) || {}
      console.log('kvMeta', kvMeta)

      const kvData = {}

      kvMeta?.forEach(item => {
        if (item.customValue) {
          kvData[item.code] = item.customValue
        }
      })
      console.log('kvData', kvData)
      this.setData({
        kvMeta,
        kvData
      })
      nodeVal['dictCode'] = dictCode
      nodeVal['refObject'] = refObject
      nodeVal['refObjectKey'] = refObjectKey
      // if (!nodeVal.name) {
      nodeVal['name'] = name
      // }

      if (value && dictCode) {
        this.initDictDeviceList({
          dictValue: value,
          dictCode
        })
      }
    }

    this.setData({
      nodeVal
    })
  },
  save() {
    const data = {
      ...this.data.data
    }

    if (data.createTime) data.createTime = +new Date(data.createTime)

    wx.request({
      url: `${domain}/admin-api/smc/scene-conf/update`,
      method: "PUT",
      data: {
        ...data,
        id: this.data.options.id,
        confNodes: this.data.confNodes
      },
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        if (res?.data?.code == '401') {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }

        if (res?.data?.code == 0) {
          wx.showToast({
            title: '保存成功',
            icon: 'none'
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 1 // 这里的delta表示返回的页面数，如果 delta 大于现有页面数，则返回到首页
            });
          }, 1000)
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },
  create() {
    const data = {
      ...this.data.data
    }

    // if (data.createTime) data.createTime = +new Date(data.createTime)

    wx.request({
      url: `${domain}/admin-api/smc/scene-conf/create`,
      method: "POST",
      data: {
        ...data,
        kind: 'config',
        confNodes: this.data.confNodes
      },
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        if (res?.data?.code == '401') {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }

        if (res?.data?.code == 0) {
          wx.showToast({
            title: '保存成功',
            icon: 'none'
          })
          setTimeout(() => {
            wx.redirectTo({
              url: '../area/index',
            })
          }, 1000)
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})